﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;

namespace EdBusTracker.V2
{
    public partial class Favs : PhoneApplicationPage
    {
        BusStops bus_stops;
        String stop;
        bool deleteMode;

        public Favs()
        {
            InitializeComponent();
            bus_stops = (BusStops)(App.Current as App).busStops;
            populateList();
            deleteMode = false;
        }

        private void buttonBack_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        void populateList()
        {
            if (bus_stops.getFavs() != null)
            {
                foreach (String k in bus_stops.getFavs().Keys)
                {
                    listBox.Items.Add(k);
                }
            }
        }

        private void buttonDelete_Click(object sender, RoutedEventArgs e)
        {
            deleteMode = true;
            MessageBox.Show("Select a favourite to remove!");
        }

        public void delete(String sn)
        {
            stop = listBox.SelectedItem.ToString();
            bus_stops.getFavs().Remove(sn);
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            using (var file = appStorage.OpenFile("favs.txt", FileMode.Create))
            using (var writer = new StreamWriter(file))
            {
                foreach (String sc in bus_stops.getFavs().Values)
                {
                    writer.Write(sc + "\n");
                }
            }
        }

        private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        { }

        private void listBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (listBox.SelectedItem == null)
            {
                return;
            }
            String sn = listBox.SelectedItem.ToString();
            if (deleteMode)
            {
                delete(sn);
                deleteMode = false;
                listBox.Items.Clear();
                populateList();
            }
            else
            {
                bus_stops.stopCode = bus_stops.getFavs()[sn];
                NavigationService.Navigate(new Uri("/V2/DisplayBusTimes.xaml", UriKind.Relative));
            }
        }
    }
}